'''养龙流程'''

import pyautogui
import pygetwindow as gw  # 导入 pygetwindow
import time
from coordinate_points import CreateDinosaur, DinosaurWarehouse, DrinkWater, DinosaurStatus, DepositDinosaur
import logging
from system_status import SystemStatus

logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')
logger = logging.getLogger(__name__)

class DinosaurBreedingProcess:

    def __init__(self, note="abc", save_note="OK", dinosaur_name="异特龙", grade="成年"):


        print(f"备注为 {note} 的 {dinosaur_name} 开始养龙")

        logger.warning(f"备注为 {note} 的 {dinosaur_name} 开始养龙")
        self.note = note
        self.save_note = save_note
        self.dinosaur_name = dinosaur_name
        self.grade = grade

        self.dinosaur_status_obj = DinosaurStatus()

        self.activate_window("恐龙岛")

    @staticmethod
    def activate_window(window_title):
        '''
        激活指定标题的窗口
        :param window_title: 窗口标题（完整或部分匹配）
        '''
        try:
            # 查找窗口
            window = gw.getWindowsWithTitle(window_title)[0]  # 获取第一个匹配的窗口
            
        except Exception as e:
            print(f"激活窗口时出错: {e}")

            SystemStatus().system_status("窗口未找到")

        else:
            if window:
                # 激活窗口
                window.activate()
                print(f"已激活窗口: {window_title}")

                time.sleep(2)  # 等待窗口加载完成
            else:
                print(f"未找到窗口: {window_title}")
                SystemStatus().system_status("窗口未找到")

    # 取龙流程
    def get_dinosaur(self):

        dw = DinosaurWarehouse()

        dw.get_coordinate() # 获取页面坐标点
        
        dw.input_note(self.note)  # 输入备注 并取出坐标点 回到创建恐龙界面

        time.sleep(2)

        cd = CreateDinosaur()

        coordinate_dict = cd.get_coordinate()  # 获取 页面龙 坐标点

        print(f"-----坐标点获取成功: {coordinate_dict}")


        if self.dinosaur_name in ["包头龙", "龙王龙", "剑龙", "三角龙", "豪勇龙"]:
            pyautogui.click(*coordinate_dict["食草恐龙"])  # 点击 食草龙
            time.sleep(1)
            pyautogui.click(*coordinate_dict[self.dinosaur_name])  # 点击 目标龙
            time.sleep(1)
        elif self.dinosaur_name in ["高脊龙", "异特龙", "牛龙", "暴君龙", "棘背龙", "始盗龙", "霸王龙", "南方巨兽龙"]:
            pyautogui.click(*coordinate_dict[self.dinosaur_name])  # 点击 目标龙

        else:
            print(f"未知龙种, 请检查")

            # SystemStatus().system_status("未知龙种")

            raise Exception("未知龙种")
        # 点击 开始游戏
        time.sleep(1)
        pyautogui.click(*coordinate_dict["开始游戏"])

    # 喝水流程
    def drink_water(self):
        # 初次进来喝水

        dw = DrinkWater()
        dw.pull_mouse()
        time.sleep(1)
        dw.find_and_click_water_button() # 查找并点击 水按钮
        self.dinosaur_status_obj.press_c_key()  # 点击 C键

        time.sleep(1)

        self.dinosaur_status_obj.get_dinosaur_status() # init 状态


    # 状态监控

    def monitor_status(self):
        '''
        获取恐龙状态 
        self.dinosaur_status = {
            "玩家": "",
            "成长": "",
            "补胃": (0, 0),
            "胃": "",
            "经验": "",
            "水": ""
            "饮水状态": False
        }

        '''
        # 监控恐龙状态

        while True:

            ds_status = self.dinosaur_status_obj.get_dinosaur_status() # 获取恐龙状态 有自动补胃功能

            # 是否在饮水
            if ds_status["饮水状态"] == False:
                print("检测到恐龙未饮水，开始喝水")
                dw = DrinkWater()
                dw.clear_screen() # 清除屏幕
                dw.pull_mouse()
                drink_status = dw.find_and_click_water_button() # 查找并点击 水按钮
                ds_status["饮水状态"] == drink_status # 饮水状态改为True

            

            # 是否成年
            if ds_status["成长"] == self.grade:


                if ds_status["经验"] == "":

                    continue

                value1, value2 = ds_status["经验"].split("/")

                if int(value1) == int(value2) or self.grade == "少年": # 少年不判断经验一般用来测试
                    print("恐龙成年，开始存龙了")
                    dd = DepositDinosaur()

                    dd.get_coordinate_a_page()  # 点击 存龙按钮

                    time.sleep(3)

                    dd.get_coordinate_b_page(self.note, self.save_note)  # 点击 确认存龙按钮

                    break

            time.sleep(10)


    def click(self, x, y):
        """点击屏幕坐标"""
        pyautogui.click(x, y, button='left')

    def move_to(self, x, y):
        """鼠标移动到屏幕坐标"""
        pyautogui.moveTo(x, y)

    def drag_to(self, x, y):
        """鼠标拖动到屏幕坐标"""
        pyautogui.dragTo(x, y, button='left')

    def type_text(self, text):
        """输入文本"""
        pyautogui.typewrite(text)

    def screenshot(self, file_path):
        """截图"""
        pyautogui.screenshot(file_path)

    def get_pixel(self, x, y):
        """获取屏幕像素"""
        return pyautogui.pixel(x, y)

    def get_position(self):
        """获取鼠标位置"""
        return pyautogui.position()

    def get_size(self):
        """获取窗口大小"""
        return self.window.size

    def get_title(self):
        """获取窗口标题"""
        return self.window.title

    def get_region(self):
        """获取窗口区域坐标"""
        return self.region


class AutoBreeding(DinosaurBreedingProcess):
    """自动养恐龙"""

    def __init__(self, note="abc", save_note="OK", dinosaur_name="异特龙", quantity=1, grade="成年"):
        super().__init__(note, save_note, dinosaur_name)

        self.quantity = quantity # 数量
        self.grade = grade # 成长等级
        self.now_quantity = 0 # 当前数量
        self.failed_quantity = 0 # 失败数量

        for i in range(self.quantity):

            # print(f"-----------第{self.now_quantity+1}次养龙----------")
            logger.info(f"-----------第{self.now_quantity+1}次养龙----------")
            try:
                self.auto_breeding()
            except Exception as e:
                logger.error(f"养龙出错: {e}")
                # SystemStatus().system_status("养龙出错")
                self.failed_quantity += 1

            self.now_quantity += 1

            time.sleep(10) # 养龙间隔 10 秒

        if self.now_quantity == self.quantity:
            
            logger.info(f"备注为 {self.note} 的 {self.quantity} 只 {self.dinosaur_name} 已经结束")

            logger.info(f"成功养了 {self.quantity-self.failed_quantity} 只 {self.dinosaur_name}")

            logger.info(f"失败了 {self.failed_quantity} 只 {self.dinosaur_name}")


    def auto_breeding(self):

        self.activate_window("恐龙岛")

        # 取龙流程
        self.get_dinosaur()

        time.sleep(15) # 取完成后等待 15 秒进入游戏

        # 进入后初次喝水流程
        self.drink_water()

        # 状态监控
        self.monitor_status()



if __name__ == '__main__':
    dino_breeding = DinosaurBreedingProcess(dinosaur_name="霸王龙")

    dino_breeding.get_dinosaur()  # 取龙流程

    #   time.sleep(20)

    #dino_breeding.drink_water() # 初次进入喝水

    #time.sleep(10)

    # dino_breeding.monitor_status()  # 状态监控
    